import string
import random
from django.conf import settings
import json
from django.db import connection
import datetime
import psutil
import time
import socket
import subprocess
import speedtest

banned_val = ['', None]

def rand_str(N):
  return ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(N))

def del_login_cookie(response):
  response.delete_cookie(key='USER_TYPE',  domain=settings.SESSION_COOKIE_DOMAIN)
  response.delete_cookie('USER_NAME',  domain=settings.SESSION_COOKIE_DOMAIN)
  response.delete_cookie('USER_EMAIL',  domain=settings.SESSION_COOKIE_DOMAIN)
  response.delete_cookie('USER_REAL_NAME',  domain=settings.SESSION_COOKIE_DOMAIN)
  response.delete_cookie('USER_PHONE',  domain=settings.SESSION_COOKIE_DOMAIN)
  response.delete_cookie('EAX_USER_INFO',  domain=settings.SESSION_COOKIE_DOMAIN)
  response.delete_cookie('vlab_session_id',  domain=settings.SESSION_COOKIE_DOMAIN)
  response.delete_cookie(settings.SESSION_COOKIE_NAME,  domain=settings.SESSION_COOKIE_DOMAIN)

def set_login_cookie(response, user):
  response.charset = 'utf8'
  max_age = 86400
  expires = datetime.datetime.strftime(
        datetime.datetime.utcnow() + datetime.timedelta(seconds=max_age),
        "%a, %d-%b-%Y %H:%M:%S GMT",
    )
  print('study.utils.set_login_cookie', user, expires, settings.SESSION_COOKIE_DOMAIN)
  response.set_cookie(key='USER_TYPE', value=user.user_type, max_age=max_age, expires=expires, domain=settings.SESSION_COOKIE_DOMAIN)
  response.set_cookie('USER_NAME', user.username.encode("utf-8"), max_age=max_age, expires=expires, domain=settings.SESSION_COOKIE_DOMAIN)
  #response.set_cookie('USER_NAME', user.username, max_age=max_age, expires=expires, domain=settings.SESSION_COOKIE_DOMAIN)
  response.set_cookie('USER_REAL_NAME', json.dumps(user.real_name), max_age=max_age, expires=expires, domain=settings.SESSION_COOKIE_DOMAIN)
  response.set_cookie('USER_PHONE', user.phone, max_age=max_age, expires=expires, domain=settings.SESSION_COOKIE_DOMAIN)
  if "e_user" in dir(user):
    response.set_cookie('EAX_USER_INFO', json.dumps(user.e_user), max_age=max_age, expires=expires, domain=settings.SESSION_COOKIE_DOMAIN)
  else:
    response.set_cookie('EAX_USER_INFO', None, max_age=max_age, expires=expires,domain=settings.SESSION_COOKIE_DOMAIN)

def get_success_url(user):
  url = settings.LOGIN_REDIRECT_URL if user.user_type == 'A' or user.user_type == 'E'  else settings.TEA_LOGIN_REDIRECT_URL if user.user_type == 'T' else settings.STU_LOGIN_REDIRECT_URL
  return url


def print_queries():
    for query in connection.queries:
        print(query['sql'])

def kill_process_by_port(port):
  process = find_process_by_port(port)
  if process:
    pid = process.info['pid']
    try:
      process_obj = psutil.Process(pid)
      process_obj.terminate()  # 发送SIGTERM信号
      # 如果进程不会正常退出，你也可以使用process_obj.kill()发送SIGKILL信号
      print(f"进程{pid}  端口{port}  已被终止")
      pass
    except psutil.NoSuchProcess:
      print("进程不存在")
      pass
  else:
    print(f"没有进程在端口 {port} 上监听")
    pass

def find_process_by_port(port):
  for process in psutil.process_iter(attrs=['pid', 'name', 'connections']):
    try:
      connections = process.info['connections']
    except (psutil.AccessDenied, psutil.NoSuchProcess):
      continue

    for conn in connections:
      if conn.status == psutil.CONN_LISTEN and conn.laddr.port == port:
        return process
  return None

def port_occupancy_check(port, host='127.0.0.1'):
    result = socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect_ex((host, int(port)))
    if result == 0:
      # 被占用
      return True
    else:
      # 没被占用
      return False

def run_onvnc(port,vnc_port):
  res = subprocess.run([
    settings.BASE_DIR + '/noVNC/utils/novnc_proxy',  # 要运行的命令行程序路径
    '--listen', str(port),  # 设置监听端口为变量 port 所代表的端口号
    '--vnc', settings.VNC_SERVER + str(5900+vnc_port),  # 指定 VNC 服务器的地址和端口
    # '--cert', settings.BASE_DIR + '/axtx.email_bundle.crt',  # 指定 SSL 证书文件路径
    # '--ssl-only',  # 仅允许 SSL 连接
    # '--key', settings.BASE_DIR + '/axtx.email.key'  # 指定 SSL 密钥文件路径
  ])
  # res = subprocess.run([
  #   settings.BASE_DIR + '/noVNC/utils/novnc_proxy',  # 要运行的命令行程序路径
  #   '--listen', str(port),  # 设置监听端口为变量 port 所代表的端口号
  #   '--vnc', host + ':5901',  # 指定 VNC 服务器的地址和端口
  #   # '--cert', settings.BASE_DIR + '/1_yianxing.com.cn_bundle.crt',  # 指定 SSL 证书文件路径
  #   '--cert', settings.BASE_DIR + '/cert.crt',  # 指定 SSL 证书文件路径
  #   '--ssl-only',  # 仅允许 SSL 连接
  #   # '--key', settings.BASE_DIR + '/2_yianxing.com.cn.key'  # 指定 SSL 密钥文件路径
  #   '--key', settings.BASE_DIR + '/cert.key'  # 指定 SSL 密钥文件路径
  # ])
  return res

def test_internet_speed():
    try:
      test = speedtest.Speedtest()
      test.get_servers()
      test.get_best_server()
      download_speed=test.download()
      upload_speed=test.upload()
      print(download_speed)
      print(upload_speed)
      download_speed_str = ""
      upload_speed_str = ""
      if download_speed<1000:
        download_speed_str = str(round(float(download_speed),2))+"bps"
      elif download_speed<1000000:
        download_speed_str = str(round(float(download_speed/1000),2))+"Kbps"
      elif download_speed<1000000000:
        download_speed_str = str(round(float(download_speed/1000/1000),2))+"Mbps"
      else:
        download_speed_str = str(round(float(download_speed/1000/1000/1000),2))+"Gbps"
      if upload_speed<1000:
        upload_speed_str = str(round(float(upload_speed),2))+"bps"
      elif upload_speed<1000000:
        upload_speed_str = str(round(float(upload_speed/1000),2))+"Kbps"
      elif upload_speed<1000000000:
        upload_speed_str = str(round(float(upload_speed/1000/1000),2))+"Mbps"
      else:
        upload_speed_str = str(round(float(upload_speed/1000/1000/1000),2))+"Gbps"
    except Exception as e:
      # print("error s" % e)
      return {
        "code": 201,
        "data": ''
      }
    else:
      return {
        "code": 200,
        "data": {
          'download_speed': download_speed_str,
          'upload_speed': upload_speed_str,
        }
      }